package com.lb.jwitter.service;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.jws.WebService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lb.jwitter.*;
import com.lb.jwitter.hibernate.*;
import com.lb.jwitter.util.ChumanoLogger;
import com.lb.jwitter.util.ConditionReport;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

@Service("tbl_CTDT_ChuyenNganhService")
@Transactional
@WebService(endpointInterface = "com.lb.jwitter.service.Tbl_CTDT_ChuyenNganhService")
public class Tbl_CTDT_ChuyenNganhServiceImpl implements Tbl_CTDT_ChuyenNganhService,Serializable {

   private Log log = LogFactory.getLog(Tbl_CTDT_ChuyenNganhServiceImpl.class);
   private static final long serialVersionUID = -8740095022264495229L;

   @Autowired
   @Qualifier("tbl_CTDT_ChuyenNganhDAO")
   private Tbl_CTDT_ChuyenNganhDAO _tbl_CTDT_ChuyenNganhDao;

   @Autowired
   @Qualifier("tbl_CTDT_KhoaDAO")
   private Tbl_CTDT_KhoaDAO _tbl_CTDT_KhoaDao;
   
   @Autowired
   @Qualifier("tbl_CTDT_MonHocDAO")
   private Tbl_CTDT_MonHocDAO _tbl_CTDT_MonHocDAO;
   
   @Autowired
   @Qualifier("tbl_CTDT_ChuyenNganh_MonHocDAO")
   private Tbl_CTDT_ChuyenNganh_MonHocDAO _tbl_CTDT_ChuyenNganh_MonHocDAO;

   public final List<Tbl_CTDT_ChuyenNganh> findAlltbl_CTDT_ChuyenNganh(int pageSize, int page){
   List<Tbl_CTDT_ChuyenNganh> result = get_tbl_CTDT_ChuyenNganhDao().findAll(pageSize, page);
       log.info("Number of user in DB:: "+result.size());
       return result;
   }

   @Transactional(noRollbackFor=IllegalArgumentException.class)
   public final Long createtbl_CTDT_ChuyenNganh(Tbl_CTDT_ChuyenNganh obj){
       return _tbl_CTDT_ChuyenNganhDao.save(obj);
   }

   public final void updatetbl_CTDT_ChuyenNganh(Tbl_CTDT_ChuyenNganh obj){
       _tbl_CTDT_ChuyenNganhDao.update(obj);
   }//end update methode

   public final Tbl_CTDT_ChuyenNganh gettbl_CTDT_ChuyenNganh (Long id){
       log.info("Try to retrieve the tbl_CTDT_ChuyenNganh: "+id);
       return get_tbl_CTDT_ChuyenNganhDao().get(id);
   }

   public void deletetbl_CTDT_ChuyenNganh(Long id){
       log.info("Try to delete the tbl_CTDT_ChuyenNganh by Id : "+ id);
       if(_tbl_CTDT_ChuyenNganhDao.exists(id)){
	    _tbl_CTDT_ChuyenNganhDao.delete(id);
       } else {
       	throw new IllegalArgumentException("EmployeeId '"+id+"' does not exists");
       }
   }

   public void deleteListtbl_CTDT_ChuyenNganh(String[] listId){
       for(String id : listId){
   	    deletetbl_CTDT_ChuyenNganh(Long.parseLong(id));
       }
   }

   public List<Tbl_CTDT_ChuyenNganh> findtbl_CTDT_ChuyenNganhByCondition(List<ConditionReport> cons,int pageSize,int page){ 
       return _tbl_CTDT_ChuyenNganhDao.findByCondition(Tbl_CTDT_ChuyenNganh.class, cons, pageSize, page); 
   } 
 
   public int counttbl_CTDT_ChuyenNganhByCondition(List<ConditionReport> cons){ 
       return _tbl_CTDT_ChuyenNganhDao.countByCondition(Tbl_CTDT_ChuyenNganh.class, cons); 
   } 
 
   public final Tbl_CTDT_ChuyenNganhDAO get_tbl_CTDT_ChuyenNganhDao() {
   	return _tbl_CTDT_ChuyenNganhDao;
   }
   
   public final void set_tbl_CTDT_ChuyenNganhDao(Tbl_CTDT_ChuyenNganhDAO obj) {
   	this._tbl_CTDT_ChuyenNganhDao = obj;
   }

   public Tbl_CTDT_KhoaDAO get_tbl_CTDT_KhoaDao() {
       return _tbl_CTDT_KhoaDao;
   }
   public void set_tbl_CTDT_KhoaDao(Tbl_CTDT_KhoaDAO _tbl_CTDT_KhoaDao) {
       this._tbl_CTDT_KhoaDao = _tbl_CTDT_KhoaDao;
   }

   public void createListtbl_CTDT_ChuyenNganhByJSON (String data ,String loaiCapNhat){
	   try{
	   ChumanoLogger.init(Tbl_CTDT_ChuyenNganhServiceImpl.class.getName());
	   ChumanoLogger.log("0BAT DAU INSERT DU LIEU");
	   List<Tbl_CTDT_ChuyenNganh> tbl_CTDT_ChuyenNganhs = new ArrayList<Tbl_CTDT_ChuyenNganh>();
	   List<Tbl_CTDT_ChuyenNganh_MonHoc> tbl_CTDT_ChuyenNganh_MonHocs = new ArrayList<Tbl_CTDT_ChuyenNganh_MonHoc>();
	   
	   JSONArray jsons = (JSONArray) JSONSerializer.toJSON( data );
		
		for(int i = 0; i < jsons.size() ; i++){
			JSONObject obj = jsons.getJSONObject(i);
			String logStr ="";
			
			//MAKHOI NAM HOCKY MONHOC STT MHBB 
			//-----------------Lay du lieu--------------------------
			//012345678
        	//DHCKCDT07
			String maKhoi = obj.getString("MAKHOI");
			//ma nganh
			String maChuyenNganh = maKhoi.substring(4, 7);
			//System.out.println(maChuyenNganh);
			
			//nam
			String nam = maKhoi.substring(7, 9);
			
			Date now = new Date();
			int year = now.getYear() + 1900;
			String yearStr = year+"";
			
			nam = yearStr.substring(0, 2) + nam;
			int namInt = Integer.parseInt(nam);
			//System.out.println(namInt);
			
			//khoa
			String khoa =  maKhoi.substring(2, 4);
			//System.out.println(khoa);
			
			//Hocky
			String n = obj.getString("NAM");
			String hk = obj.getString("HOCKY");
			int hocky = (Integer.parseInt(n) - namInt)*2 + Integer.parseInt(hk);
			//System.out.println(hocky);
			
			//Mon hoc
			String maMonHoc = obj.getString("MONHOC");
			//System.out.println(maMonHoc);
			
			//BB/TC
			String bb = obj.getString("MHBB");
			String loaiBB = (bb.equals("x"))? "BB": "TC";
			//System.out.println(bb);
			
			logStr ="[ " + (i+1)+ " - " 
				+ "CN: " + maChuyenNganh + " - " 
				+ "KHOA: " + khoa + " - " 
				+ "KHOAHOC: " + nam + " - " 
				+ "MH: " + maMonHoc + " - " 
				+ "LOAI: " + loaiBB + "]";
			//======================================================
			//tim khoa
	        List<Long> khoaId = findKhoaId(khoa);
	        if(khoaId == null || khoaId.size() == 0 ){
	        	ChumanoLogger.log(logStr + " NOT KHOA");
	        	continue;
	        }
	        Tbl_CTDT_Khoa kkhoa = new Tbl_CTDT_Khoa();
        	kkhoa.setId(new Long(khoaId.get(0)));
	        
			//tim chuyen nganh
	        List<Long> chuyenNganhId = findChuyenNganhId(maChuyenNganh);
	        Tbl_CTDT_ChuyenNganh tbl_CTDT_ChuyenNganh = new Tbl_CTDT_ChuyenNganh();
	        if(chuyenNganhId == null || chuyenNganhId.size() == 0 ){
	        	//set chuyen nganh
	        	tbl_CTDT_ChuyenNganh.setKhoaId(kkhoa); 
	        	tbl_CTDT_ChuyenNganh.setMa(maChuyenNganh);
	            tbl_CTDT_ChuyenNganhs.add(tbl_CTDT_ChuyenNganh);
	            
	            //chua co thi tao moi
	            chuyenNganhId = new ArrayList<Long>();
	            Long id = _tbl_CTDT_ChuyenNganhDao.save(tbl_CTDT_ChuyenNganh);
	            chuyenNganhId.add(id);
	            logStr+= " NEW CN";
	        }
	        tbl_CTDT_ChuyenNganh.setId(chuyenNganhId.get(0)); 
	        
	        //tim mon hoc
	        List<Long> monHocId = findMonHocId(maMonHoc);
	        if(monHocId == null || monHocId.size() == 0 ){
	        	ChumanoLogger.log(logStr + " NOT MH");
	        	continue;
	        }
	        Tbl_CTDT_MonHoc tbl_CTDT_MonHoc = new Tbl_CTDT_MonHoc();
	        tbl_CTDT_MonHoc.setId(new Long(monHocId.get(0)));
	        //--------------------------------------------------
	        //===================================================
	        Tbl_CTDT_ChuyenNganh_MonHoc tbl_CTDT_ChuyenNganh_MonHoc = new Tbl_CTDT_ChuyenNganh_MonHoc();
	        tbl_CTDT_ChuyenNganh_MonHoc.setChuyenNganhId(tbl_CTDT_ChuyenNganh);
	        tbl_CTDT_ChuyenNganh_MonHoc.setKhoaHoc(namInt);
	        tbl_CTDT_ChuyenNganh_MonHoc.setHocKy(""+hocky);
	        tbl_CTDT_ChuyenNganh_MonHoc.setMonHocId(tbl_CTDT_MonHoc);
	        tbl_CTDT_ChuyenNganh_MonHoc.setMaLoaiBB(loaiBB);

	        List<Long> Ids = findChuyenNganhMonHocId(tbl_CTDT_ChuyenNganh.getId(),tbl_CTDT_MonHoc.getId(),namInt);
	        if(Ids!=null && Ids.size()>0)
	        	tbl_CTDT_ChuyenNganh_MonHoc.setId(Ids.get(0));
	        
	       
	        tbl_CTDT_ChuyenNganh_MonHocs.add(tbl_CTDT_ChuyenNganh_MonHoc); 
	        
	        //LOGGING
	        ChumanoLogger.log(logStr);
	         
		}//end for
		
		//-----------------------SAVE ALL --------------------
		//_tbl_CTDT_ChuyenNganhDao.saveOrUpdateAll(tbl_CTDT_ChuyenNganhs);
		_tbl_CTDT_ChuyenNganh_MonHocDAO.saveOrUpdateAll(tbl_CTDT_ChuyenNganh_MonHocs);
		
		
	   }
	   catch (Exception e) {
		// TODO: handle exception
		   ChumanoLogger.log("ERROR: " +e.getMessage());
		   System.out.println("------------ERROR CHUMANO-------------");
		   e.printStackTrace();
		   System.out.println("=================================");
	   }
	   
	   ChumanoLogger.stop();
   }
   
   private List<Long> findChuyenNganhId(String maChuyenNganh){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 ConditionReport con = new ConditionReport(); 
            con.setCol("ma");
            con.setValue1(maChuyenNganh);
            con.setOperator("eq");
            cons.add(con);	
       }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
	   List<Long> chuyenNganhId = _tbl_CTDT_ChuyenNganhDao.findColumnByCondition(Tbl_CTDT_ChuyenNganh.class,cons,columns, 1, 1);
	   return chuyenNganhId;
   }
   
   private List<Long> findKhoaId(String maKhoa){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 ConditionReport con = new ConditionReport(); 
            con.setCol("ma");
            con.setValue1(maKhoa);
            con.setOperator("eq");
            cons.add(con);	
       }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
       List<Long> khoaId = _tbl_CTDT_KhoaDao.findColumnByCondition(Tbl_CTDT_Khoa.class, cons,columns, 1, 1);
	   return khoaId;
   }
   
   private List<Long> findMonHocId(String maMonHoc){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 ConditionReport con = new ConditionReport(); 
            con.setCol("ma");
            con.setValue1(maMonHoc);
            con.setOperator("eq");
            cons.add(con);	
       }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
       List<Long> monHocId = _tbl_CTDT_MonHocDAO.findColumnByCondition(Tbl_CTDT_MonHoc.class, cons,columns, 1, 1);
	   return monHocId;
   }
   
   private List<Long> findChuyenNganhMonHocId(Long chuyenNganhId, Long monHocId, int khoaHoc){
	   List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
       {
       	 ConditionReport con = new ConditionReport(); 
            con.setCol("chuyenNganhId.id");
            con.setValue1(chuyenNganhId);
            con.setOperator("eq");
            cons.add(con);	
       }
       
       {
         	 ConditionReport con = new ConditionReport(); 
              con.setCol("monHocId.id");
              con.setValue1(monHocId);
              con.setOperator("eq");
              cons.add(con);	
         }
       
       {
         	 ConditionReport con = new ConditionReport(); 
              con.setCol("khoaHoc");
              con.setValue1(khoaHoc);
              con.setOperator("eq");
              cons.add(con);	
         }
       List<String> columns = new ArrayList<String>();
       columns.add("id");
       
       List<Long> Ids = _tbl_CTDT_ChuyenNganh_MonHocDAO.findColumnByCondition(Tbl_CTDT_ChuyenNganh_MonHoc.class, cons,columns, 1, 1);
	   return Ids;
   }

}//endclass

